import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/common/common_types.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/udt_tb_workreportrecord_odoo_api.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/udt_tb_workreportrecord.dart';
import 'package:flutter_admin/pages/common/date_time_select.dart';
import 'package:flutter_admin/pages/common/years_date_time.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_workreportrecord/udt_tb_workreportrecord_edit.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_workreportrecord/udt_tb_workreportrecord_dialog.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_workreportrecord/udt_tb_workreportrecord_print.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_workreportrecord/udt_tb_workreportrecord_qrscan_except_banjin_list.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_workreportrecord/udt_tb_workreportrecord_qrscan_list.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

import 'udt_tb_workreportrecord_qrscan.dart';

class UdtTbWorkreportrecordList extends StatefulWidget {
  UdtTbWorkreportrecordList({Key? key}) : super(key: key);

  @override
  _UdtTbWorkreportrecordListState createState() =>
      _UdtTbWorkreportrecordListState();
}

class _UdtTbWorkreportrecordListState extends State<UdtTbWorkreportrecordList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<CryDataTableState> tableKey1 = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  UdtTbWorkreportrecord udtTbWorkreportrecord = UdtTbWorkreportrecord();
  UdtTbWorkreportrecord udtTbWorkreportrecordScan = UdtTbWorkreportrecord();
  List<UdtTbWorkreportrecord> selectedList = [];

  //车间
  List<SelectOptionVO> workshopList = [];

  //工位
  List<SelectOptionVO> stationList = [];

  //状态
  List<SelectOptionVO> statusList = [];

  //报工人员
  List<SelectOptionVO> reportworkerList = [];

  //工序列表
  List<SelectOptionVO> pathList = [];

  late var _subscription;

  late var _subscription1;

  DateFormat format = DateFormat('yyyy-MM-dd HH:mm:ss');

  UserInfo userInfo = StoreUtil.getCurrentUserInfo();

  bool isTeamLeader = false;

  ValueNotifier<bool> isLoading = ValueNotifier<bool>(true);
  @override
  void initState() {
    udtTbWorkreportrecord.reportDateStart = Utils.getDate()+" 00:00:00";
    udtTbWorkreportrecord.reportDateEnd = Utils.getDate()+" 23:59:59";
    _subscription = EventBus.getSubscriber()
        .where((event) => event["key"] == "workreportrecord")
        .listen(_onEnvent);
    _subscription1 = EventBus.getSubscriber()
        .where((event) => event["key"] == "workreportrecordDelete")
        .listen(_scanDelete);
    super.initState();

    WidgetsBinding.instance!.addPostFrameCallback((c) {
      if (isDisplayDesktop(Cry.context)) {
        _loadSelectVO();
      }else{
        _query();
      }
    });
  }

  @override
  void dispose() {
    _subscription.cancel();
    _subscription1.cancel();
    super.dispose();
  }

  _loadSelectVO() async {
    if (userInfo.major != null) {
      workshopList = await DynamicDataApi.getModelSelect(
          model: "hr.department",
          name: "complete_name",
          key: "parent_id",
          operator: "!=",
          val: null);
    } else {
      if( isDisplayDesktop(context) && userInfo.teamsInfo!.length != 0 ){
        isTeamLeader = true;
        udtTbWorkreportrecord.teamId = userInfo.teamsInfo![0][0].toString();
        udtTbWorkreportrecord.teamName = userInfo.teamsInfo![0][1];
        stationList = await DynamicDataApi.getModelSelect(
            model: "base.productionstation",
            name: "stationname",
            key: 'team_id',
            val: userInfo.teamsInfo![0][0]);
      }else{
        stationList = await DynamicDataApi.getModelSelect(
            model: "base.productionstation",
            name: "stationname",
            key: 'workshop_id',
            val: int.parse(userInfo.deptId!));
        udtTbWorkreportrecord.workshopId = userInfo.deptId;
      }
    }
    statusList = [
      SelectOptionVO(value: "", label: ""),
      SelectOptionVO(value: "0", label: "未确认"),
      SelectOptionVO(value: "1", label: "已确认"),
    ];
    setState(() {});
    _query();
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          userInfo.major != null
              ? CrySelect(
                  width: 280,
                  label: '生产车间',
                  dataList: workshopList,
                  value: udtTbWorkreportrecord.workshopId,
                  onSaved: (v) {
                    udtTbWorkreportrecord.workshopId = v;
                  },
                  onChange: (v) async {
                    if (udtTbWorkreportrecord.workshopId != v) {
                      formKey.currentState!.save();
                      udtTbWorkreportrecord.workshopId = v;
                      udtTbWorkreportrecord.stationId = null;
                      try {
                        stationList = await DynamicDataApi.getModelSelect(
                            model: "base.productionstation",
                            name: "stationname",
                            key: 'workshop_id',
                            val: int.parse(v));
                      } catch (e) {
                        stationList = [];
                      }
                      setState(() {});
                    }
                  },
                )
              : isTeamLeader?CryInput(
            width: 200,
            label: '班组',
            enable: false,
            value: udtTbWorkreportrecord.teamName,
            onSaved: (v) {
              udtTbWorkreportrecord.teamName = v;
            },
          ):CryInput(
                  width: 200,
                  label: '生产车间',
                  enable: false,
                  value: userInfo.deptName,
                ),
          CrySelect(
            width: 280,
            label: '设备工位',
            dataList: stationList,
            value: udtTbWorkreportrecord.stationId,
            onSaved: (v) {
              udtTbWorkreportrecord.stationId = v;
            },
          ),
          CryInput(
            width: 140,
            label: '产品名称',
            value: udtTbWorkreportrecord.productName,
            onSaved: (v) {
              udtTbWorkreportrecord.productName = v;
            },
          ),
          CryInput(
            width: 140,
            label: '生产单号',
            value: udtTbWorkreportrecord.productionorderno,
            onSaved: (v) {
              udtTbWorkreportrecord.productionorderno = v;
            },
          ),
          CrySelect(
            width: 160,
            dataList: statusList,
            label: '是否确认',
            value: udtTbWorkreportrecord.status,
            onSaved: (v) {
              udtTbWorkreportrecord.status = v;
            },
          ),
          DateTimeSelect(
            context,
            width: 230,
            label: '报工开始时间',
            value: udtTbWorkreportrecord.reportDateStart,
            lastDate: isNotBlank(udtTbWorkreportrecord.reportDateEnd)
                ? format.parse(udtTbWorkreportrecord.reportDateEnd!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              udtTbWorkreportrecord.reportDateStart = v;
              setState(() {});
            },
            onSaved: (v) {
              udtTbWorkreportrecord.reportDateStart = v;
            },
          ),
          DateTimeSelect(
            context,
            width: 230,
            label: '报工结束时间',
            value: udtTbWorkreportrecord.reportDateEnd,
            firstDate: isNotBlank(udtTbWorkreportrecord.reportDateStart)
                ? format.parse(udtTbWorkreportrecord.reportDateStart!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              udtTbWorkreportrecord.reportDateEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              udtTbWorkreportrecord.reportDateEnd = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              Tooltip(
                message: '生产报工',
                child: IconButton(
                  icon: Icon(Icons.add),
                  onPressed: () {
                    _qrscan();
                  },
                ),
              ),
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('是否确认')),
        DataColumn(label: Text('工厂名称')),
        DataColumn(label: Text('车间名称')),
        DataColumn(label: Text('生产单号')),
        DataColumn(label: Text('产品图号')),
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('材料型号')),
        DataColumn(label: Text('生产工序')),
        DataColumn(label: Text('合格数量')),
        DataColumn(label: Text('不合格数量')),
        DataColumn(label: Text('备货数量')),
        DataColumn(label: Text('换模个数')),
        DataColumn(label: Text('刀数')),
        DataColumn(label: Text('备注')),
        DataColumn(label: Text('班次')),
        DataColumn(label: Text('班组名称')),
        DataColumn(label: Text('设备工位')),
        DataColumn(label: Text('报工人')),
        DataColumn(label: Text('报工日期')),
        DataColumn(label: Text('修改人')),
        DataColumn(label: Text('修改日期')),
      ],
      getCells: (m) {
        UdtTbWorkreportrecord udtTbWorkreportrecord =
        UdtTbWorkreportrecord.fromMap(m);
        TextStyle textStyle = udtTbWorkreportrecord.qualifiedquantity!>udtTbWorkreportrecord.planQty!?TextStyle(color: Colors.red):TextStyle();
        return [
          DataCell(Text((udtTbWorkreportrecord.status == '')
              ? '--'
              : (udtTbWorkreportrecord.status == "0")
              ? '未确认'
              : '已确认',style: textStyle,)),
          DataCell(Text(udtTbWorkreportrecord.factoryName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.workshopName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.productionorderno ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.productCode ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.productName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.spec ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.processName ?? '--',style: textStyle)),
          DataCell(Text((udtTbWorkreportrecord.qualifiedquantity != null)
              ? udtTbWorkreportrecord.qualifiedquantity.toString()
              : '--',style: textStyle)),
          DataCell(Text((udtTbWorkreportrecord.unqualifiedquantity != null)
              ? udtTbWorkreportrecord.unqualifiedquantity.toString()
              : '--',style: textStyle)),
          DataCell(Text((udtTbWorkreportrecord.repairquantity != null)
              ? udtTbWorkreportrecord.repairquantity.toString()
              : '--',style: textStyle)),
          DataCell(Text((udtTbWorkreportrecord.replacenumber != null)
              ? udtTbWorkreportrecord.replacenumber.toString()
              : '--',style: textStyle)),
          DataCell(Text((udtTbWorkreportrecord.cutting != null)
              ? udtTbWorkreportrecord.cutting.toString()
              : '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.remark ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.shiftName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.teamName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.stationName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.reportworkerName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.reportDate ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.writeName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.writeDate!,style: textStyle)),
        ];
      },
    );
    CryDataTable table1 = CryDataTable(
      key: tableKey1,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
        Tooltip(
          message: '生产报工',
          child: IconButton(
            icon: Icon(Icons.add),
            onPressed: () {
              _qrscan();
            },
          ),
        ),
        _operationList(),
      ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('是否确认')),
        DataColumn(label: Text('工厂名称')),
        DataColumn(label: Text('车间名称')),
        DataColumn(label: Text('生产单号')),
        DataColumn(label: Text('产品编码')),
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('生产工序')),
        DataColumn(label: Text('合格数量')),
        DataColumn(label: Text('不合格数量')),
        DataColumn(label: Text('返修数量')),
        DataColumn(label: Text('产品类型')),
        DataColumn(label: Text('备注')),
        DataColumn(label: Text('班次')),
        DataColumn(label: Text('班组名称')),
        DataColumn(label: Text('设备工位')),
        DataColumn(label: Text('报工人')),
        DataColumn(label: Text('报工日期')),
        DataColumn(label: Text('修改人')),
        DataColumn(label: Text('修改日期')),
      ],
      getCells: (m) {
        UdtTbWorkreportrecord udtTbWorkreportrecord =
        UdtTbWorkreportrecord.fromMap(m);
        TextStyle textStyle = TextStyle();
        if(udtTbWorkreportrecord.qualifiedquantity!=null && udtTbWorkreportrecord.planQty != null){
          textStyle = udtTbWorkreportrecord.qualifiedquantity!>udtTbWorkreportrecord.planQty!?TextStyle(color: Colors.red):TextStyle();
        }
        return [
          DataCell(Text((udtTbWorkreportrecord.status == '')
              ? '--'
              : (udtTbWorkreportrecord.status == "0")
              ? '未确认'
              : '已确认',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.factoryName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.workshopName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.productionorderno ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.productCode ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.productName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.spec ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.processName ?? '--',style: textStyle)),
          DataCell(Text((udtTbWorkreportrecord.qualifiedquantity != null)
              ? udtTbWorkreportrecord.qualifiedquantity.toString()
              : '--',style: textStyle)),
          DataCell(Text((udtTbWorkreportrecord.unqualifiedquantity != null)
              ? udtTbWorkreportrecord.unqualifiedquantity.toString()
              : '--',style: textStyle)),
          DataCell(Text((udtTbWorkreportrecord.repairquantity != null)
              ? udtTbWorkreportrecord.repairquantity.toString()
              : '--',style: textStyle)),
          DataCell(Text((udtTbWorkreportrecord.repairStatus == '1')
              ? "返修产品"
              : '非返修产品',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.remark ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.shiftName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.teamName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.stationName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.reportworkerName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.reportDate ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.writeName ?? '--',style: textStyle)),
          DataCell(Text(udtTbWorkreportrecord.writeDate!,style: textStyle)),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButtons.edit(
            context,
            selectedList.length == 1 && selectedList[0].status == '0'
                ? () => _edit(selectedList[0])
                : null),
        CryButtons.delete(
            context,
            selectedList.length != 0 && _checkStatus(selectedList)
                ? () => _delete(selectedList)
                : null),
        CryButton(
            label: '确认',
            iconData: Icons.confirmation_num,
            onPressed: selectedList.length != 0 && _checkStatus(selectedList)
                ? () => _confirm(selectedList)
                : null),
        CryButton(
          label: "导出",
          onPressed: () => _generateExcel(),
          iconData: Icons.import_export_outlined,
        )
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: StoreUtil.hasData("type") && (StoreUtil.read("type")==2)?table1:table)),
        ],
      ),
    );
    return result;
  }

  _edit(UdtTbWorkreportrecord? udtTbWorkreportrecord) async {
    StoreUtil.write("key", "workreportrecordEdit");
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) => Dialog(
        child: UdtTbWorkreportrecordEdit(
          udtTbWorkreportrecord: udtTbWorkreportrecord,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if(udtTbWorkreportrecord == null){
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  void _scanDelete(dynamic obj) async{
    try {
      ResponseBodyApi res = await DynamicDataApi.getModels(
          model: "res.users", key: 'login', val: obj["scan"]);
      if (res.success!) {
        if (res.data.length == 0) {
          CryUtils.message("该人员不存在");
          return;
        } else if (res.data.length > 1) {
          CryUtils.message("编号重复");
          return;
        } else {
          if (selectedList[0].reportworkerId !=
              res.data[0]["id"].toString()) {
            CryUtils.message("您没有权限");
            setState(() {});
            return;
          }
          isLoading.value = false;
        }
      }
    } catch (e) {
      print(e);
      // CryUtils.message(e.toString());
      return;
    }
  }

  void deleteConfirm(BuildContext context, String content, onConfirm) {
    StoreUtil.write("key", "workreportrecordDelete");
    isLoading.value = true;
    showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return ValueListenableBuilder<bool>(
          valueListenable: isLoading,
          builder: (context, value, child) {
            return AlertDialog(
              title: Text(S.of(context).information),
              content: value?Text("请扫描人员",style: TextStyle(
                  fontSize: 36, color: Colors.red
              ),):Text(content),
              actions: <Widget>[
                TextButton(
                  child: Text(S.of(context).cancel),
                  onPressed: () {
                    Navigator.of(context).pop();
                    StoreUtil.write("key", "workreportrecord");
                  },
                ),
                TextButton(
                  child: Text(S.of(context).confirm),
                  onPressed: value?null:() {
                    Navigator.of(context).pop();
                    onConfirm(context);
                    StoreUtil.write("key", "workreportrecord");
                  },
                ),
              ],
            );
          },
        );
      },
    );
  }

  _delete(List<UdtTbWorkreportrecord> selectedList) async {
    if(isDisplayDesktop(context)){
      cryConfirm(context, S.of(context).confirmDelete, (context) async {
        List ids = selectedList.map((v) {
          return int.parse(v.id!);
        }).toList();
        var result = await UdtTbWorkreportrecordOdooApi.removeByIds(ids);
        if (result.success!) {
          CryUtils.message("删除成功");
          _query();
        }
      });
    }else{
      deleteConfirm(context, S.of(context).confirmDelete, (context) async {
        List ids = selectedList.map((v) {
          return int.parse(v.id!);
        }).toList();
        var result = await UdtTbWorkreportrecordOdooApi.removeByIds(ids);
        if (result.success!) {
          CryUtils.message("删除成功");
          _query();
        }
      });
    }
  }

  _reset() {
    udtTbWorkreportrecord = UdtTbWorkreportrecord();
    // udtTbWorkreportrecord.reportDate =
    //     DateFormat('yyyy-MM-dd').format(new DateTime.now());
    udtTbWorkreportrecord.reportDateStart = Utils.getDate()+" 00:00:00";
    udtTbWorkreportrecord.reportDateEnd = Utils.getDate()+" 23:59:59";
    if (userInfo.major != null) {
      stationList = [];
    }else{
      udtTbWorkreportrecord.workshopId = userInfo.deptId;
    }
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    if(StoreUtil.hasData("type") && StoreUtil.read("type")==2){
      tableKey1.currentState?.pageTo(0);
    }else{
      tableKey.currentState?.pageTo(0);
    }
    _loadData();
  }

  _loadData() async {
    var filter = {};
    if (udtTbWorkreportrecord.productName != null &&
        udtTbWorkreportrecord.productName != "") {
      filter = {
        "product.template": [
          'product_id',
          ['name', 'like', '%${udtTbWorkreportrecord.productName}%']
        ]
      };
    }
    // 手机端需要先绑定工位再进行查看
    if (!isDisplayDesktop(Cry.context)) {
      if (!StoreUtil.hasData(Constant.KEY_PRODUCTIONSTATION) ||
          !StoreUtil.hasData(Constant.KEY_REPORTWORKERLIST)) {
        CryUtils.message("请先绑定设备工位");
        return;
      }
      udtTbWorkreportrecord.stationId =
          StoreUtil.read(Constant.KEY_PRODUCTIONSTATION)["stationId"];
    }
    ResponseBodyApi responseBodyApi =
        await UdtTbWorkreportrecordOdooApi.page(data: {
      "page": page,
      "domainList": udtTbWorkreportrecord.toDomainList(),
      "filter": filter
    });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      if(StoreUtil.hasData("type") && StoreUtil.read("type")==2) {
        tableKey1.currentState!.loadData(page);
      }else{
        tableKey.currentState!.loadData(page);
      }
      _getSelectList();
    }
  }

  Future<dynamic> findAll() async {
    formKey.currentState?.save();
    List<UdtTbWorkreportrecord> resultList = [];
    var filter = {};
    if (udtTbWorkreportrecord.productName != null &&
        udtTbWorkreportrecord.productName != "") {
      filter = {
        "product.template": [
          'product_id',
          ['name', 'like', '%${udtTbWorkreportrecord.productName}%']
        ]
      };
    }
    ResponseBodyApi responseBodyApi =
        await UdtTbWorkreportrecordOdooApi.findAll(data: {
      "domainList": udtTbWorkreportrecord.toDomainList(),
      "filter": filter
    });
    if (responseBodyApi.success!) {
      resultList = responseBodyApi.data
              .map<UdtTbWorkreportrecord>(
                  (e) => UdtTbWorkreportrecord.fromMap(e))
              .toList() ??
          [];
    } else {
      return;
    }
    return resultList;
  }

  _generateExcel() async {
    List<UdtTbWorkreportrecord> selectedList = await findAll();
    if (selectedList == null) {
      return;
    }
    List<Map> map = [
      {
        'name': 'factoryName',
        'label': '工厂名称',
        'columnWidth': 12.0,
      },
      {
        'name': 'workshopName',
        'label': '车间名称',
        'columnWidth': 19.0,
      },
      {
        'name': 'productionorderno',
        'label': '生产单号',
        'columnWidth': 23.0,
      },
      {
        'name': 'productCode',
        'label': '产品图号',
        'columnWidth': 12.0,
      },
      {
        'name': 'productName',
        'label': '产品名称',
        'columnWidth': 12.0,
      },
      {
        'name': 'spec',
        'label': '材料型号',
        'columnWidth': 20.0,
      },
      {
        'name': 'qualifiedquantity',
        'label': '合格数量',
        'columnWidth': 12.0,
      },
      {
        'name': 'unqualifiedquantity',
        'label': '不合格数量',
        'columnWidth': 15.0,
      },
      {
        'name': 'repairquantity',
        'label': '备货数量',
        'columnWidth': 12.0,
      },
      {
        'name': 'replacenumber',
        'label': '换模个数',
        'columnWidth': 12.0,
      },
      {
        'name': 'cutting',
        'label': '刀数',
        'columnWidth': 12.0,
      },
      {
        'name': 'remark',
        'label': '备注',
        'columnWidth': 12.0,
      },
      {
        'name': 'shiftName',
        'label': '班次',
        'columnWidth': 10.0,
      },
      {
        'name': 'teamName',
        'label': '班组名称',
        'columnWidth': 19.0,
      },
      {
        'name': 'stationName',
        'label': '设备工位',
        'columnWidth': 12.0,
      },
      {
        'name': 'reportworkerName',
        'label': '报工人',
        'columnWidth': 10.0,
      },
      {
        'name': 'reportDate',
        'label': '报工日期',
        'columnWidth': 20.0,
      },
      {
        'name': 'writeName',
        'label': '修改人',
        'columnWidth': 10.0,
      },
      {
        'name': 'writeDate',
        'label': '修改日期',
        'columnWidth': 20.0,
      }
    ];
    Utils.generateExcel(fileName: "生产报工信息", configure: map, data: selectedList);
  }

  _search() {
    return showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) => Dialog(
        child: UdtTbWorkreportrecordDialog(),
      ),
    ).then((v) {
      if (v != null) {
        udtTbWorkreportrecord = v;
        _query();
      }
    });
  }

  _qrscan() async{
    if(!StoreUtil.hasData("type")){
      CryUtils.message("请先绑定设备工位");
      return;
    }
    if(StoreUtil.read("type") == 0){
      // 箱体厂，批量报工 钣金车间报工
      if (!StoreUtil.hasData(Constant.KEY_PRODUCTIONSTATION) ||
          !StoreUtil.hasData(Constant.KEY_REPORTWORKERLIST)
      //|| !StoreUtil.hasData(Constant.KEY_PATHLIST)
      ) {
        CryUtils.message("请先绑定设备工位");
        return;
      }
      StoreUtil.write("key", "workreportrecordQrscan");
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) => Dialog(
          child: UdtTbWorkreportrecordQrscanList(),
        ),
      ).then((v) {
        if (v != null) {
          _query();
        }
      });
    }else if(StoreUtil.read("type") == 1){
      // 箱体厂，批量报工
      if (!StoreUtil.hasData(Constant.KEY_PRODUCTIONSTATION) ||
          !StoreUtil.hasData(Constant.KEY_REPORTWORKERLIST)
      //|| !StoreUtil.hasData(Constant.KEY_PATHLIST)
      ) {
        CryUtils.message("请先绑定设备工位");
        return;
      }
      StoreUtil.write("key", "workreportrecordQrscan");
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) => Dialog(
          child: UdtTbWorkreportrecordQrscanExceptBanJinList(),
        ),
      ).then((v) {
        if (v != null) {
          _query();
        }
      });
    }else{
      // 器件厂，单次报工
      if (!StoreUtil.hasData(Constant.KEY_PRODUCTIONSTATION) ||
          !StoreUtil.hasData(Constant.KEY_REPORTWORKERLIST) ||
          !StoreUtil.hasData(Constant.KEY_PATHLIST)
      ) {
        CryUtils.message("请先绑定设备工位");
        return;
      }
      StoreUtil.write("key", "workreportrecordQrscan");
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) => Dialog(
          child: UdtTbWorkreportrecordQrscan(),
        ),
      ).then((v) {
        if (v != null) {
          _query();
        }
      });
    }
  }

  bool _checkStatus(List<UdtTbWorkreportrecord> selectedList) {
    for (var i = 0; i < selectedList.length; i++) {
      if (selectedList[i].status == '1') return false;
    }
    return true;
  }

  _confirm(List<UdtTbWorkreportrecord> selectedList) async {
    cryConfirm(context, "是否确认", (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await UdtTbWorkreportrecordOdooApi.changeStatus(ids);
      if (result.success!) {
        if (result.data["code"] == "500") {
          CryUtils.message(result.data["message"]);
          return;
        }
        _loadData();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _print() {
    StoreUtil.write("key", "workreportrecordPrint");
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) => Dialog(
        child: UdtTbWorkreportrecordPrint(),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  //处理扫码获得的code
  void _onEnvent(dynamic obj) {
    try {
      _getStation(obj["scan"].toString());
    } catch (e) {
      print(e);
      // CryUtils.message(e.toString());
      return;
    }
  }

  _getStation(barcode) async {
    // todo 设备工位
    ResponseBodyApi res = await DynamicDataApi.getModels(
        model: "base.productionstation", key: 'stationcode', val: barcode);
    if (res.success!) {
      if (res.data.length == 0) {
        CryUtils.message("该设备工位编码已失效");
        return;
      } else if (res.data.length > 1) {
        CryUtils.message("设备工位编码重复");
        return;
      } else {
        var factoryCode = "XTC";
        ResponseBodyApi res1 = await DynamicDataApi.getModels(
            model: "hr.department", key: 'id', val: res.data[0]["factory_id"][0]);
        if(res1.success!){
          factoryCode = res1.data[0]["department_code"];
        }
        // 查找对应班组
        ResponseBodyApi teamRes = await DynamicDataApi.getModels(
            model: "base.team", key: 'id', val: res.data[0]["team_id"][0]);
        if (!teamRes.success!) {
          return;
        }
        if (teamRes.data.length == 0) {
          CryUtils.message("数据错误");
          return;
        }
        // formKey.currentState!.save();
        udtTbWorkreportrecordScan.stationId = res.data[0]["id"].toString();
        udtTbWorkreportrecordScan.stationCode = barcode;
        udtTbWorkreportrecordScan.stationName =
            res.data[0]["stationname"].toString();
        udtTbWorkreportrecordScan.factoryId =
            res.data[0]["factory_id"][0].toString();
        udtTbWorkreportrecordScan.factoryName =
            res.data[0]["factory_id"][1].toString();
        udtTbWorkreportrecordScan.workshopId =
            res.data[0]["workshop_id"][0].toString();
        udtTbWorkreportrecordScan.workshopName =
            res.data[0]["workshop_id"][1].toString();
        udtTbWorkreportrecordScan.teamId = teamRes.data[0]["id"].toString();
        udtTbWorkreportrecordScan.teamCode =
            teamRes.data[0]["teamcode"].toString();
        udtTbWorkreportrecordScan.teamName =
            teamRes.data[0]["teamname"].toString();
        // if(udtTbWorkreportrecord.teamCode == 'PTPFA'
        //     ||udtTbWorkreportrecord.teamCode == 'PTPFB'
        //     ||udtTbWorkreportrecord.teamCode == 'PTPFC'){
        //   quantTitle = '喷涂面积';
        // }
        // todo 获取该班组下的所有人员
        ResponseBodyApi resUser = await DynamicDataApi.getModels(
            model: "base.teamuser", key: "team_id", val: teamRes.data[0]["id"]);
        if (resUser.success!) {
          if (resUser.data.length == 0) {
            CryUtils.message("该班组下没有人员,请绑定人员");
            return;
          }
          reportworkerList = [];
          for (int i = 0; i < resUser.data.length; i++) {
            reportworkerList.add(SelectOptionVO(
                value: resUser.data[i]["staff_id"][0].toString(),
                label: resUser.data[i]["staff_id"][1].toString()));
          }
          bool flag = true;
          // todo 获取工位下的工序
          ResponseBodyApi stationPath = await DynamicDataApi.getModels(
              model: "base.teampath",
              key: "team_id",
              val: teamRes.data[0]["id"]);
          if (stationPath.success! && stationPath.data.length != 0) {
            var pathList = [];
            for (int i = 0; i < stationPath.data.length; i++) {
              pathList.add(SelectOptionVO(
                  value: stationPath.data[i]["process_id"][0].toString(),
                  label: stationPath.data[i]["process_id"][1].toString()));
            }
            StoreUtil.write(Constant.KEY_PATHLIST, pathList);
          } else {
            flag = false;
            StoreUtil.remove(Constant.KEY_PATHLIST);
          }
          if(factoryCode == "XTC"){
            CryUtils.message("绑定${udtTbWorkreportrecordScan.stationName}设备工位成功");
            StoreUtil.write(Constant.KEY_PRODUCTIONSTATION,
                udtTbWorkreportrecordScan.toMap());
            StoreUtil.write(Constant.KEY_REPORTWORKERLIST, reportworkerList);
            var workshopCode = "BJ";
            ResponseBodyApi res1 = await DynamicDataApi.getModels(
                model: "hr.department", key: 'id', val: num.parse(udtTbWorkreportrecordScan.workshopId!));
            if(res1.success!){
              workshopCode = res1.data[0]["department_code"];
            }
            if(workshopCode == 'BJ'){
              StoreUtil.write("type", 0);
            }else{
              StoreUtil.write("type", 1);
            }
            _query();
            _qrscan();
          }
          if(factoryCode == "QJC"){
            if(flag){
              CryUtils.message("绑定${udtTbWorkreportrecordScan.stationName}设备工位成功");
              StoreUtil.write(Constant.KEY_PRODUCTIONSTATION,
                  udtTbWorkreportrecordScan.toMap());
              StoreUtil.write(Constant.KEY_REPORTWORKERLIST, reportworkerList);
              StoreUtil.write("type", 2);
              _query();
              _qrscan();
            }else{
              CryUtils.message("班组${udtTbWorkreportrecordScan.teamName}下没有工序，请绑定工序");
            }
          }
          setState(() {});
        }
      }
    }
  }

  _getSelectList() {
    if(StoreUtil.hasData("type") && StoreUtil.read("type")==2) {
      selectedList = tableKey1.currentState
          ?.getSelectedList(page)
          .map<UdtTbWorkreportrecord>((e) => UdtTbWorkreportrecord.fromMap(e))
          .toList() ??
          [];
    }else{
      selectedList = tableKey.currentState
          ?.getSelectedList(page)
          .map<UdtTbWorkreportrecord>((e) => UdtTbWorkreportrecord.fromMap(e))
          .toList() ??
          [];
    }

    setState(() {});
  }

  test(){
    _onEnvent({"scan":"ZTKD-KDLJ-LJDJ-001"});
    // _onEnvent({"scan":"ZTKD-KDBJ-BJZW-019"});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          // todo 偷个懒 哈哈
          test();
        } else if (v == OperationType.delete) {
          _delete(selectedList);
        } else if (v == OperationType.print) {
          _print();
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.dmsFile) {
          // todo 我又偷懒了
          _confirm(selectedList);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1 && selectedList[0].status == '0',
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1 && selectedList[0].status == '0',
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.print,
          child: ListTile(
            leading: const Icon(Icons.print),
            title: Text('打印流程卡'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length == 1 && selectedList[0].status == '0',
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length == 1 && selectedList[0].status == '0',
            title: Text('删除'),
          ),
        ),
        // PopupMenuItem<OperationType>(
        //   value: OperationType.add,
        //   child: ListTile(
        //     leading: const Icon(Icons.print),
        //     title: Text('test1'),
        //   ),
        // ),
      ],
    );
  }
}
